package com.bw.module_device.view

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.PopupMenu
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bw.lib_base.path.RouterPath
import com.bw.lib_common.view.BaseMvvmActivity
import com.bw.module_device.R
import com.bw.module_device.databinding.ActivityDeviceBinding
import com.bw.module_device.viewmodel.DeviceViewModel
import com.bw.module_main.adapter.DeviceAdapter
import com.google.android.material.dialog.MaterialAlertDialogBuilder

/**
 * 智慧园区-01-设备管理-v1.1-吴熙-20250507
 */
@Route(path = RouterPath.PATH_DEVICE_ACTIVITY)
class DeviceActivity : BaseMvvmActivity<ActivityDeviceBinding>() {

    lateinit var deviceAdapter: DeviceAdapter
    private val viewModel by lazy { ViewModelProvider(this)[DeviceViewModel::class.java] }

    override fun initView() {
        //头布局
        mDataBinding.goBack.setOnClickListener { finish() }
        mDataBinding.title.text="设备管理"
        mDataBinding.goAdd.visibility=View.GONE
        mDataBinding.goMore.visibility=View.VISIBLE

        //列表
        deviceAdapter=DeviceAdapter()
        mDataBinding.rv.layoutManager=LinearLayoutManager(this)
        mDataBinding.rv.adapter=deviceAdapter


        //弹出菜单跳转到新增设备
        mDataBinding.goMore.setOnClickListener {
            //创建PopMenu
            val popupMenu=PopupMenu(this,it)
            //加载菜单资源
            popupMenu.menuInflater.inflate(R.menu.menu_device,popupMenu.menu)
            //设置菜单的监听事件
            popupMenu.setOnMenuItemClickListener {
                when(it.itemId){
                    R.id.menu1->{
                        ARouter.getInstance().build("/addDevice/addDevice").navigation()
                        true
                    }
                    else -> true
                }
            }
            popupMenu.show()
        }

        //点击item跳转到设备详情
        deviceAdapter.setOnItemClickListener { adapter, view, position ->

            ARouter.getInstance().build("/detailDevice/detailDevice")
                .withSerializable("device",deviceAdapter.getItem(position))
                .withInt("deviceId",deviceAdapter.getItem(position).id)
                .navigation()
        }

        //长按删除巡检
        deviceAdapter.setOnItemLongClickListener { adapter, view, position ->
            showDeleteConfirmationDialog(context = this, onDeleteConfirmed = {
                // 用户点击确认后的删除逻辑
                deleteItem(position)
            })
            true
        }

        //监听搜索框
        mDataBinding.etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                if (s.toString().length>0){
                    searchDevice(s.toString())
                }else{
                    viewModel.getDeviceList()
                }
            }
        })
    }

    //搜索设备
    private fun searchDevice(keyword: String) {
        val iterator = deviceAdapter.data.iterator()
        while (iterator.hasNext()) {
            val device = iterator.next()
            if (!device.deviceName.contains(keyword) && !device.installationLocation.contains(keyword)) {
                iterator.remove() // 删除
                deviceAdapter.notifyDataSetChanged()

                if (deviceAdapter.data.size==0){
                    ToastUtils.showShort("未搜索到${keyword}")
                    return
                }
            }
        }
    }

    // 删除设备
    private fun deleteItem(position:Int) {
        viewModel.deleteDevice(deviceAdapter.data[position].id)
        deviceAdapter.notifyItemRemoved(position)
    }


    // 封装通用的删除提示对话框
    private fun showDeleteConfirmationDialog(
        context: Context,
        onDeleteConfirmed: () -> Unit
    ) {
        MaterialAlertDialogBuilder(context)
            .setTitle("删除确认")
            .setMessage("确定要删除此项吗？")
            .setPositiveButton("删除") { _, _ ->
                onDeleteConfirmed()
            }
            .setNegativeButton("取消", null)
            .setIcon(R.drawable.icon_remove_black)
            .show()
    }


    override fun observeDataChange() {
        viewModel.getDeviceListSuccess.observe(this){
            deviceAdapter.data.clear()
            deviceAdapter.data.addAll(it.reversed())
            deviceAdapter.notifyDataSetChanged()
        }

        viewModel.deleteDeviceSuccess.observe(this){
            ToastUtils.showLong("删除成功")
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_device

    override fun onResume() {
        super.onResume()
        viewModel.getDeviceList()
    }
}